﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Meraz.Core.Parsers
{
    public class HotAirParser : RegexBlogParser
    {
        public HotAirParser() { this.BlogKey = BlogKeyType.HotAir; }
        internal override List<string> ParseAliases(string source)
        {
            if (alias == null)
                ParseByLine(source);
            return new List<string> { alias };
        }
        string rawDateString = null;
        string alias = null;
        const string bylinePattern = @"<h4>posted at (?<DATE>.+) by (?<ALIAS>.+?)\s*<br />";
        void ParseByLine(string source)
        {
            Match match = Regex.Match(source, bylinePattern);
            if (!match.Success)
                return;
            rawDateString = match.Groups["DATE"].Value;
            alias = match.Groups["ALIAS"].Value;
        }

        internal override DateTime ParseDate(string source)
        {
            if (string.IsNullOrWhiteSpace(rawDateString))
                ParseByLine(source);
            string[] tokens = rawDateString.Split(new string[] { " on " }, StringSplitOptions.RemoveEmptyEntries);
            return DateTime.Parse(tokens[1] + " " + tokens[0]);
        }

        internal override string ParseBody(string source)
        {
            string startMarker = @"<div id=""page-post"">";
            string endMarker = @"<div id=""comments-section"">";
            int start = source.IndexOf(startMarker);
            int end = source.IndexOf(endMarker, start);
            if (end < start)
                return null;
            start += startMarker.Length;
            string result = source.Substring(start, end - start);
            start = result.IndexOf("</h4>") + 5;
            result = result.Remove(0, start);
            result = RemoveTags("script", result);
            result = RemoveTags("noscript", result);

            return result;
        }
        internal override void CleanUp(Model.PostValues post)
        {
            post.Links.Remove("http://www.facebook.com/sharer.php");
        }
    }
}
